<template>
  <div class="landlord-orders-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="title">房东订单管理</h2>
      <el-button
          type="primary"
          @click="goBack"
          class="back-btn"
      >
        返回房东中心
      </el-button>
    </div>

<!--    &lt;!&ndash; 筛选条件 &ndash;&gt;-->
<!--    <div class="filter-container">-->
<!--      <el-form :inline="true" :model="filterForm" class="filter-form">-->
<!--        <el-form-item label="订单状态">-->
<!--          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>-->
<!--            <el-option-->
<!--                v-for="status in statusOptions"-->
<!--                :key="status.value"-->
<!--                :label="status.label"-->
<!--                :value="status.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="房源ID">-->
<!--          <el-input v-model="filterForm.house_id" placeholder="输入房源ID" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="租客ID">-->
<!--          <el-input v-model="filterForm.tenant_id" placeholder="输入租客ID" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" @click="handleFilter">筛选</el-button>-->
<!--          <el-button @click="resetFilter">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </div>-->

    <!-- 订单列表容器 -->
    <div class="orders-list-container">
      <!-- 订单列表 -->
      <div class="orders-list">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><loading /></el-icon>
          <span>加载中...</span>
        </div>

        <!-- 空状态 -->
        <div v-else-if="orders.length === 0" class="empty-container">
          <el-empty description="暂无订单数据" />
        </div>

        <!-- 订单卡片列表 -->
        <div v-else>
          <el-card
              v-for="order in orders"
              :key="order.order_id"
              class="order-card"
              shadow="hover"
          >
            <div class="card-content">
              <!-- 订单基本信息 -->
              <div class="order-header">
                <div class="order-no">
                  <span>订单编号：</span>
                  <strong>{{ order.order_no }}</strong>
                </div>
                <div class="order-status">
                  <el-tag :type="getStatusTagType(order.status)">
                    {{ formatOrderStatus(order.status) }}
                  </el-tag>
                  <el-button
                      v-if="order.status === 'pending'"
                      type="primary"
                      size="small"
                      @click="handleConfirm(order.order_id)"
                  >
                    确认订单
                  </el-button>
                </div>
              </div>

              <!-- 房源和租客信息 -->
              <div class="info-section">
                <div class="info-item">
                  <span class="label">房源ID：</span>
                  <span>{{ order.house_id }}</span>
                </div>
                <div class="info-item">
                  <span class="label">租客ID：</span>
                  <span>{{ order.tenant_id }}</span>
                </div>
              </div>

              <!-- 租期信息 -->
              <div class="info-section">
                <div class="info-item">
                  <span class="label">租期：</span>
                  <span>{{ order.start_date }} 至 {{ order.end_date }}</span>
                </div>
                <div class="info-item">
                  <span class="label">总金额：</span>
                  <span class="amount">¥{{ order.total_amount }}</span>
                </div>
              </div>

              <!-- 订单时间 -->
              <div class="info-section">
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span>{{ order.created_at }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                    v-if="order.status === 'pending' || order.status === 'confirmed'"
                    type="danger"
                    size="small"
                    @click="handleCancel(order.order_id)"
                >
                  取消订单
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="viewOrderDetail(order.order_id)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalOrders"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import common_util from "../../util/common_util.js";

const router = useRouter()

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)

// 筛选表单
const filterForm = ref({
  status: '',
  house_id: '',
  tenant_id: ''
})

// 状态选项
const statusOptions = ref([
  { value: 'pending', label: '待确认' },
  { value: 'confirmed', label: '已确认' },
  { value: 'canceled', label: '已取消' },
  { value: 'completed', label: '已完成' }
])

// 订单数据
const orders = ref([])
const loading = ref(false)

// 订单状态映射
const orderStatusMap = {
  pending: '待确认',
  confirmed: '已确认',
  canceled: '已取消',
  completed: '已完成'
}

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      per_page: pageSize.value,
      ...filterForm.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '') {
        delete params[key]
      }
    })

    const response = await axios.get('/api/orders/landlord', {
      params,
      headers: common_util.accessHeader()
    })

    if (response.data.code === 0) {
      orders.value = response.data.data
      totalOrders.value = response.data.total || orders.value.length
    } else {
      ElMessage.error(response.data.msg || '获取订单列表失败')
    }
  } catch (error) {
    handleRequestError(error)
  } finally {
    loading.value = false
  }
}

// 格式化订单状态
const formatOrderStatus = (status) => {
  return orderStatusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    confirmed: 'success',
    canceled: 'danger',
    completed: 'info'
  }
  return typeMap[status] || ''
}

// 确认订单
const handleConfirm = (orderId) => {
  ElMessageBox.confirm('确定要确认此订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.put(`/api/orders/${orderId}`, {
        status: 'confirmed',
        cancel_reason: '订单确认'
      }, {
        headers: common_util.accessHeader()
      })

      if (response.data.code === 0) {
        ElMessage.success('订单已确认')
        fetchOrders() // 刷新列表
      } else {
        ElMessage.error(response.data.msg || '确认订单失败')
      }
    } catch (error) {
      handleRequestError(error)
    }
  }).catch(() => {})
}

// 取消订单
const handleCancel = (orderId) => {
  ElMessageBox.confirm('确定要取消此订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.put(`/api/orders/${orderId}`, {
        status: 'canceled',
        cancel_reason: '房东取消'
      }, {
        headers: common_util.accessHeader()
      })

      if (response.data.code === 0) {
        ElMessage.success('订单已取消')
        fetchOrders() // 刷新列表
      } else {
        ElMessage.error(response.data.msg || '取消订单失败')
      }
    } catch (error) {
      handleRequestError(error)
    }
  }).catch(() => {})
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push({ name: 'order-detail', params: { orderId } })
}

// 返回房东中心
const goBack = () => {
  router.push({ name: 'LandlordCenter' })
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    status: '',
    house_id: '',
    tenant_id: ''
  }
  handleFilter()
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchOrders()
}

const handlePageChange = () => {
  fetchOrders()
}

// 错误处理
const handleRequestError = (error) => {
  if (error.response) {
    if (error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push({ name: 'Login' })
    } else {
      ElMessage.error(`服务器错误: ${error.response.status}`)
    }
  } else if (error.request) {
    ElMessage.error('请求超时，请检查网络连接')
  } else {
    ElMessage.error(`请求错误: ${error.message}`)
  }
}

// 初始化加载订单
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.landlord-orders-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.back-btn {
  margin-left: auto;
}

.filter-container {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.orders-list-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.orders-list {
  min-height: min-content;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-icon {
  font-size: 40px;
  margin-bottom: 10px;
  animation: rotate 2s linear infinite;
}

.empty-container {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.order-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.order-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-no {
  font-size: 16px;
}

.order-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-section {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.info-item {
  margin-right: 20px;
  margin-bottom: 8px;
  min-width: 200px;
}

.label {
  color: #666;
  min-width: 80px;
  display: inline-block;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  flex-shrink: 0;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 滚动条样式 */
.orders-list-container::-webkit-scrollbar {
  width: 6px;
}

.orders-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.orders-list-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.orders-list-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>